<template>
  <div class="search-container" v-loading="isLoading">
    <div style="display: flex">
      <el-text>设备ID：</el-text>
      <div style="margin-left: 10px">
        <el-select
          v-model="deviceStore.currentNodeId"
          filterable
          clearable
          style="width: 240px"
          placeholder="请选择要查询的设备ID"
        >
          <el-option v-for="item in deviceStore.nodeIds" :key="item" :label="item" :value="item" />
        </el-select>
      </div>
      <div style="padding-left: 20px">
        <el-button type="primary" :icon="Search" @click="onSearch">检索配置</el-button>
      </div>
      <div style="padding-left: 10px">
        <el-button :icon="Refresh" @click="onRefresh">刷新设备ID列表</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useDeviceManagerStore } from '@/stores/device/manager'
import { ElMessage } from 'element-plus'
import { DeviceServerClient } from '@/api/axios/device-server-client'
import { Search, Refresh } from '@element-plus/icons-vue'
const client = new DeviceServerClient(import.meta.env.VITE_DEVICE_SERVER_BASE_URL)
const deviceStore = useDeviceManagerStore()
const isLoading = ref<boolean>(false)

if (!deviceStore.alreadySetNodeIds) {
  onRefresh()
}

async function onRefresh() {
  isLoading.value = true
  let result = await client.getIdsAsync()

  if (!result.isSuccess) {
    ElMessage.error(result.message)
  } else {
    if (result.result.length == 0) {
      ElMessage.info('设备ID列表为空！')
    } else {
      deviceStore.nodeIds = result.result
      ElMessage.success('ID列表已更新！')
    }
  }
  isLoading.value = false
}

async function onSearch() {
  if (deviceStore.currentNodeId == '' || deviceStore.currentNodeId == null) {
    ElMessage.error('请选择要查询的设备ID')
    return
  }
  isLoading.value = true
  let result = await client.getDeviceConfigsAsync(deviceStore.currentNodeId)

  if (result.isSuccess) {
    deviceStore.currentNode = {
      nodeId: deviceStore.currentNodeId,
      deviceConfigs: result.result
    }
    if (result.result.length == 0) {
      ElMessage.info('该设备没有任何配置！')
    } else {
      ElMessage.success('配置列表已更新！')
    }
  } else {
    ElMessage.error(result.message)
  }
  isLoading.value = false
}
</script>

<style scoped>
.search-container {
  padding: 20px 30px 10px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
